from multiprocessing import Process
import time
import psutil
from libs.conn import *
from libs.test_clients import test_clients_process
from libs.check_alarm import check_alarm_process, check_notcie_process
from libs.check_service import check_iperf3_service_process
from libs.test_model import test_model_process

CHECK_ALARM_PID = -1
CHECK_NOTICE_PID = -1
TEST_CLIENTS_PID = -1
CHECK_IPERF3_SERVICE_PID = -1
TEST_MODEL_PID = -1

def is_process_running(pid):
    """检查 PID 是否对应一个有效进程"""
    try:
        process = psutil.Process(pid)
        return process.is_running()
    except psutil.NoSuchProcess:
        return False
    except psutil.AccessDenied:
        return True  # 无权限访问，假设进程仍存在
    except Exception as e:
        log_error(f"检查进程时出错: {str(e)}")
        return False

def check_process():
    global CHECK_ALARM_PID, CHECK_NOTICE_PID, TEST_CLIENTS_PID, CHECK_IPERF3_SERVICE_PID, TEST_MODEL_PID
    if not is_process_running(CHECK_ALARM_PID):
        CHECK_ALARM_PID = check_alarm_process()
        log_info('开启报警检查线程, pid: ' + str(CHECK_ALARM_PID))
    if not is_process_running(CHECK_NOTICE_PID):
        CHECK_NOTICE_PID = check_notcie_process()
        log_info('开启通知检查线程, pid: ' + str(CHECK_NOTICE_PID))
    if not is_process_running(TEST_CLIENTS_PID):
        TEST_CLIENTS_PID = test_clients_process()
        log_info('开启客户端检查线程, pid: ' + str(TEST_CLIENTS_PID))
    if not is_process_running(CHECK_IPERF3_SERVICE_PID):
        CHECK_IPERF3_SERVICE_PID = check_iperf3_service_process()
        log_info('开启iperf3服务检查线程, pid:'+ str(CHECK_IPERF3_SERVICE_PID))
    if not is_process_running(TEST_MODEL_PID):
        TEST_MODEL_PID = test_model_process()
        log_info('开启模型检查线程, pid:'+ str(TEST_MODEL_PID))
    
def check_log():
    # 检查日志是否达到最大数量，如果达到则自动归档（自动归档到前一天）
    log_maxcount = int(get_config('log_maxcount'))
    limit_time = datetime.now()
    current_log_count = int(fetchvalue("SELECT COUNT(*) FROM logs WHERE log_time < ?", (limit_time.strftime('%Y-%m-%d'), )))
    if current_log_count > log_maxcount:
        archive_log_count, archive_path = archive_logs(limit_time - timedelta(days=1))
        message = f"日志数量超过限制数 {log_maxcount}，自动归档日志数量 {archive_log_count}，归档路径 {archive_path}"
        execute("INSERT INTO system_logs (log_content, log_time) VALUES (?, ?)", (message, get_time()))
        log_info(message)

def global_run():
    while True:
        log_info('开启全局线程，一分钟一次')
        try:
            check_process()
            check_log()
        except Exception as e:
            log_error(f"Global thread error occurred: {str(e)}")
        
        time.sleep(60)


def global_process():
    p = Process(target=global_run)
    #p.daemon = True # 设置为守护进程，如果主进程退出，子进程也会退出
    p.start()
    return p.pid